package com.wavecoler.professor.servlets;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.codehaus.jettison.json.JSONArray;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;

import com.google.gson.Gson;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.wavecoler.professor.objects.Word;

public class AddProblem extends HttpServlet{

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		
		Client service = Client.create();
		WebResource webResource = service.resource("http://wavecoler.lag.itesm.mx:8080/WaveColerWebServices/rest/words");
		ClientResponse respuesta = webResource.accept("application/json").get(ClientResponse.class);
		final JSONObject jsonOb = respuesta.getEntity(JSONObject.class);	
		
		try {
			JSONArray  dictionary = jsonOb.getJSONArray("word");
			
			ArrayList<Word> palabrotas = new ArrayList<Word>();
			
			for(int i = 0; i < dictionary.length();i++){
				JSONObject bli = dictionary.getJSONObject(i);
				Gson gsons = new Gson();
				BufferedReader brs = new BufferedReader(new StringReader(bli.toString()));
				Word palabrota = gsons.fromJson(bli.toString(), Word.class);
				System.out.println("Agregue:  $%&!" + palabrota.getMainWord()  );
				palabrotas.add(palabrota);
			}
			
			HttpSession session = req.getSession();
			session.setAttribute("palabrotas", palabrotas);
			String address = "jsps/AddProblem.jsp";
		    RequestDispatcher dispatcher = req.getRequestDispatcher(address);
		    dispatcher.forward(req, resp);		
			
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

}
